<template>
  <div>
    <div class="search__example--wrap">
      <com-search
        :data="searchData"
        @search-submit="searchSubmit"
        @reset-submit="resetSubmit"
      />
    </div>

    <com-table
      v-loading="loading"
      :columns="columns"
      :data="tableData"
      :summary-method="getSummaries"
      show-summary
      :pagination="{
        currentPage: defalutParams.pageIndex,
        total: total,
        onSizeChange: handleSizeChange,
        onCurrentChange: handleCurrentChange
      }"
      @selection-change="handleSelectionChange"
    >
      <template #price="scope">
        <el-tag type="success">
          ￥{{ scope.row.price }}
        </el-tag>
      </template>
      <template #income="scope">
        <el-tag type="success">
          ￥{{ scope.row.income }}
        </el-tag>
      </template>
    </com-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import InfoWrite from './components/InfoWrite.vue'
import Detail from './components/Detail.vue'
import FacePay from './components/FacePay.vue'
import { useExample } from '@/hooks/useExample'
import { Message } from '_c/Message'

import { getListApi, delsApi, nativePayApi, huaBeiPayApi } from './api'
import { formatTime } from '@/utils'

const searchData = [
  {
    label: '订单编号',
    value: '',
    itemType: 'input',
    field: 'orderNo',
    placeholder: '请输入订单编号',
    clearable: true
  }
]

export default defineComponent({
  // name: 'ExampleDialog',
  components: {
    InfoWrite,
    Detail,
    FacePay
  },
  setup() {
    const info = ref<any>(null)
    const columns = ref<any[]>([
      {
        field: 'index',
        type: 'index',
        label: '序号',
        width: 60,
        index: (index: number) => {
          return (defalutParams.pageIndex - 1) * defalutParams.pageSize + index + 1
        }
      },
      {
        field: 'createDate',
        label: '交易日期',
        formatter: (row: any, column: any, cellValue: any, index: number) => {
          return formatTime(row.createDate, 'yyyy-MM-dd')
        },
        width: 100

      },
      {
        field: 'memberId',
        label: '会员编号',
        width: 100
      },
      {
        field: 'courseId',
        label: '课程编号',
        width: 100
      },
      {
        field: 'orderNo',
        label: '订单编号',
        showOverflowTooltip: true
      },
      {
        field: 'courseName',
        label: '课程名称',
        showOverflowTooltip: true
      },
      {
        field: 'price',
        label: '课程售价',
        slots: {
          default: 'price'
        },
        width: 100
      },
      {
        field: 'income',
        label: '课程收益',
        slots: {
          default: 'income'
        },
        width: 100
      }
    ])

    const {
      defalutParams,
      tableData,
      loading,
      total,
      dialogVisible,
      title,
      currentChange,
      sizeChange,
      handleSelectionChange,
      selectionData,
      delData,
      comName,
      toggleVisible
    } = useExample()

    // 请求数据
    async function getExampleList(data?: any): Promise<void> {
      try {
        const res = await getListApi({
          params: Object.assign(defalutParams, data || {})
        })
        total.value = res.count
        tableData.value = res.data
      } finally {
        loading.value = false
      }
    }

    // 查询
    function searchSubmit(data: any) {
      // 该方法重置了一些默认参数
      currentChange(1)
      getExampleList(data)
    }

    // 重置
    function resetSubmit(data: any) {
      // 该方法重置了一些默认参数
      currentChange(1)
      getExampleList(data)
    }

    // 展示多少条
    function handleSizeChange(val: number) {
      // 该方法重置了一些默认参数
      sizeChange(val)
      getExampleList()
    }

    // 展示第几页
    function handleCurrentChange(val: number) {
      // 该方法重置了一些默认参数
      currentChange(val)
      getExampleList()
    }

    // 删除多选
    function dels(item?: any) {
      delData(async() => {
        let ids: number[] = []
        if (item.id) {
          ids.push(item.id)
        } else {
          ids = selectionData.value.map((v: any) => {
            return v.id
          })
        }
        const res = await delsApi({
          data: JSON.stringify(ids)
        })
        if (res.status === 200) {
          Message.success(res.message)
          getExampleList()
        }
      }, { hiddenVerify: item.id, text: '此操作将申请退款, 是否继续?' })
    }

    // 打开弹窗
    function open(row: any, component: string) {
      comName.value = component
      title.value = !row ? '新增' : (component === 'Detail' ? '刷脸付' : '当面付（打开支付宝扫一扫）')
      info.value = row || null
      toggleVisible(true)
    }

    // 成功之后的回调
    function success(type: string) {
      if (type === 'add') {
        currentChange(1)
      }
      toggleVisible()
      getExampleList()
    }

    getExampleList()

    // 合计
    function getSummaries(param: { columns: any; data: any }) {
      const { columns, data } = param
      const sums: any[] = []
      columns.forEach((column: { property: string | number }, index: number) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item: { [x: string]: any }) => Number(item[column.property]))
        if (index === 6 || index === 7 && !values.every((value: number) => isNaN(value))) {
          sums[index] = values.reduce((prev: any, curr: any) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })

      return sums
    }

    return {
      getSummaries,
      info, open,
      searchData, searchSubmit, resetSubmit,
      columns,
      defalutParams,
      loading,
      tableData,
      total,
      title,
      dialogVisible,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      dels,
      close, success,
      comName,
      toggleVisible
    }
  }
})
</script>

<style>
</style>
